# coding=utf-8
from . import models
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from rest_framework.views import APIView
from rest_framework import exceptions
# from rest_framework.pagination import CursorPagination
from User.views import getUser
from User.models import User_Token
# 用户认证
from User.utils.auth import TokenAuth
from User.utils.permission import CadrePermission
from Work.utils.ser import *
import json
import urllib.request
import os
import time
import socket
import uuid



class group(APIView):
    """
        post:
            # 
            Title: 增加组
            Request: title
            Return: /
            Permissions: TokenAuth-CadrePermission
        delete:
            # 
            Title: 删除组
            Request: id
            Return: /
            Permissions: TokenAuth-CadrePermission
        put:
            # 
            Title: 修改组
            Request: title-id
            Return: /
            Permissions: TokenAuth-CadrePermission
        get:
            # 
            Title: 查看组
            Request: /
            Return: data
            Permissions: TokenAuth-CadrePermission
    """
    def post(self, request, *args, **kwargs):
        ret = {'code': 2000}
        user  = getUser(request)
        print(request.data)
        title = request.data['title']
        print(user,title)
        dic = {"title":title,"userID":user}
        models.WorkClass.objects.create(**dic)   
        
        return JsonResponse(ret)

    def delete(self, request, *args, **kwargs):
        id = request.data['id']
        print(request.data)
        user  = getUser(request)
        models.WorkClass.objects.get(id=id,userID=user).delete()
        ret = {'code': 2000}
        return JsonResponse(ret)

    def put(self, request, *args, **kwargs):
        id = request.data['id']
        title = request.data['title']
        user  = getUser(request)
        obj = models.WorkClass.objects.get(id=id,userID=user)
        obj.title = title
        obj.save()
        ret = {'code': 2000}
        return JsonResponse(ret)

    def get(self, request, *args, **kwargs):
        ret = {'code': 2000}
        user  = getUser(request)
        _list = models.WorkClass.objects.filter(userID = user)
        ser = GroupGetSer(instance=_list,many=True).data
        ret['data'] = ser
        return JsonResponse(ret)
class work(APIView):
    """
        post:
            # 
            Title: 增加作业
            Request: title-id-msg
            Return: data
            Permissions: TokenAuth-CadrePermission
        delete:
            # 
            Title: 删除作业
            Request: id
            Return: /
            Permissions: TokenAuth-CadrePermission
        put:
            # 
            Title: 修改作业
            Request: title-id-msg
            Return: /
            Permissions: TokenAuth-CadrePermission
        get:
            # 
            Title: 查看作业
            Request: id
            Return: data
            Permissions: TokenAuth-CadrePermission
    """
    authentication_classes = [TokenAuth, ]
    permission_classes = [CadrePermission,]
    def post(self, request, *args, **kwargs):
        ret = {'code': 2000}
        user  = getUser(request)
        id = request.data['id']
        title = request.data['title']
        msg = request.data['msg']
        workClass = models.WorkClass.objects.get(id = id)
        dic = {"title":title,"workClass":workClass,"msg":msg}
        obj = models.Work.objects.create(**dic) 
        ret['data'] = obj.id
        return JsonResponse(ret)

    def delete(self, request, *args, **kwargs):
        ret = {'code': 2000}
        id = request.data['id']
        models.Work.objects.get(id=id).delete()  #存在跨用户操作，特别危险
        return JsonResponse(ret)

    def put(self, request, *args, **kwargs):
        ret = {'code': 2000}
        id = request.data['id']
       
        title = request.data['title']
        msg = request.data['msg']
        obj = models.Work.objects.get(id=id)  #存在跨用户操作，特别危险
        obj.title = title
        obj.msg = msg
        obj.save()
        return JsonResponse(ret)

    def get(self, request, *args, **kwGETargs):
        ret = {'code': 2000}
        user  = getUser(request)
        id = request.GET['id']
        print(id)
        # return JsonResponse(ret)
        workClass = models.WorkClass.objects.get(userID = user,id=id)
        _list = models.Work.objects.filter(workClass = workClass)
        ser = WorkGetSer(instance=_list,many=True).data
        ret['data'] = ser
        return JsonResponse(ret)

class work_id(APIView):
  def get(self, request, *args, **kwargs):
        ret = {'code': 2000}
        id = request.GET['id']
        obj = models.Work.objects.get(id = id)
        ret['data'] = {'title':obj.title,'msg':obj.msg}
        return JsonResponse(ret)

def workUserState(workUser):
    if workUser.state == "False":
        workUser.state = "True"
    else:
        workUser.state = "False"
    workUser.save()

class auditor(APIView):
    """
        post:
            # 
            Title: 审核学生
            Request: id-workID
            Return: /
            Permissions: TokenAuth-CadrePermission
    """
    authentication_classes = [TokenAuth, ]
    permission_classes = [CadrePermission,]
    def post(self, request, *args, **kwargs):
        ret = {'code': 2000}
        id = request.data['id']
        workID = request.data['workID']
        if workID:
            workOBJ = models.Work.objects.get(id = workID)
            workUser = models.WorkUser.objects.filter(work=workOBJ)
            for obj in workUser:
                obj.state = "True"
                obj.save()
            return JsonResponse(ret)
        workUser = models.WorkUser.objects.get(id = id)
        workUserState(workUser)

class UserWork_id(APIView):
    """
        get:
            #
            Title: 学生单个作业完成详情
            Request: id
            Return:data
            Permissions: TokenAuth-CadrePermission
    """
    authentication_classes = [TokenAuth, ]
    # permission_classes = [CadrePermission,]
    def get(self, request, *args, **kwargs):
        ret = {'code': 2000}     
        user = getUser(request)
        workID = request.GET['id']
        workOBJ = models.Work.objects.get(id = workID)
        workUser = models.WorkUser.objects.get(user = user,work=workOBJ)
        ret['state'] = workUser.state
        
        img_list = models.WorkIMG.objects.filter(WorkUser = workUser)
        ser = ImgUrlGetSer(instance=img_list,many=True).data
        ret['porteait'] = ser
        return JsonResponse(ret)
class UserWork(APIView):
    """
        get:
            #
            Title: 单个作业每个学生完成详情
            Request: id
            Return:data
            Permissions: TokenAuth-CadrePermission
    """
    authentication_classes = [TokenAuth, ]
    permission_classes = [CadrePermission,]
    def get(self, request, *args, **kwargs):
        ret = {'code': 2000}     
        user = getUser(request)
        workID = request.GET['id']
        workOBJ = models.Work.objects.get(id = workID)  #存在同权限跨用户执行
        workUser = models.WorkUser.objects.filter(work=workOBJ)
        data = workUserSer(instance=workUser,many=True).data
        print(data)
        ret['data'] = data
        return JsonResponse(ret)

        

def submit_imgDE(request):
    res={}
    if(request.method == 'POST'):
        WorkIMGID = request.POST.get("id", None)
        obj = models.WorkIMG.objects.get(id=WorkIMGID)
        os.remove(obj.url)
        print(obj.url)
        obj.delete()

    return JsonResponse(res)
    

def submit_file(request):
    res={}
    myFile =request.FILES.get("file", None)
    return JsonResponse(res)


def submit_fileDE(request):
    res={}
    if(request.method == 'POST'):
        WorkIMGID = request.POST.get("id", None)
        print(WorkIMGID)
        models.WorkIMG.objects.get(id=WorkIMGID).delete()
    return JsonResponse(res)
    

class details(APIView):
    def get(self,request):
        ret={"code":000,"data":{"workName":"null","workMsg":"null"}}
        workID = request.GET['workID'] 
        obj =models.Work.objects.get(id=workID)
        ret["code"] = 200                              
        ret["data"]["workName"]=obj.title                                                   
        ret["data"]["workMsg"]=obj.msg                                                          
        return JsonResponse(ret)

class userwork(APIView):
    """
        post:
            #
            Title:
            Request:workID
            Return:code,data(state,imgUrl)
            Permission: /
    """
    def get(self,request):
        try:
            ret = {"code":2000,"data":{"state":"未提交","imgUrl":""}}
            workIdGet = request.GET["workID"]
            workObj = models.Work.objects.get(id=workIdGet)
            WorkUserObj = models.WorkUser.objects.get(user=getUser(request).id,work=workObj.id)
            WorkIimgObj = models.WorkIMG.objects.get(WorkUser=WorkUserObj.id)
            ret["data"]["state"] =WorkUserObj.get_state_display()
            ret["data"]["imgUrl"] =WorkIimgObj.url
            # pass
        except:
            ret["data"]["code"] = 5000
        return JsonResponse(ret)

def upFile(myFile,url,name):
    if not myFile:  
        print("没有文件")
        return
    print(url,name)
    destination = open(os.path.join(url,name),'wb+')    # 打开特定的文件进行二进制的写操作  
    for chunk in myFile.chunks():      # 分块写入文件  
        destination.write(chunk) 
    print("保存文件")
     
    destination.close()
    
def submit_img(request):
    '''
        上传无验证
    '''
    res={}
    if(request.method == 'POST'):
        
        url = "/media/HomeWork/"
        myFile = request.FILES.get("file", None)
        name = str(time.time()) + "__" + myFile.name
        workID = int(request.POST.get("workID", None))
        token = request.POST.get("token", None)
        hostname = socket.gethostname()
        
        userObj = User_Token.objects.filter(token=token).first().user
        workObj =models.Work.objects.get(id=workID)
        WorkUser = models.WorkUser.objects.get_or_create(work = workObj,user=userObj)
        WorkUser[0].state = "None"
        WorkUser[0].save()
        WorkIMGObj = models.WorkIMG.objects.get_or_create(WorkUser = WorkUser[0])[0]
        if(WorkIMGObj.url!="" and len(WorkIMGObj.url)!=0):
            path = settings.BASE_DIR + WorkIMGObj.url
            path = path.replace(settings.SERVER_URL, '')
            if os.path.exists(path):  # 如果文件存在
                os.remove(path)  
        upFile(myFile,settings.BASE_DIR+url,name) #保存文件
        WorkIMGObj.url = settings.SERVER_URL+url+name
        WorkIMGObj.save()
    return JsonResponse(res)
